package com.upload.web;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/files")
public class UploadController {
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void upload(@RequestParam("myFileName") MultipartFile file, HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException {
		String path = session.getServletContext().getRealPath("")+"\\upload";
		//获取文件后缀
		String oldName = file.getOriginalFilename();
		String suffix = oldName.substring(oldName.lastIndexOf(".") + 1);
		
		String fileName = UUID.randomUUID().toString() + "." + suffix;
		File dir = new File(path, fileName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		file.transferTo(dir);
		String uploadPath = "";
		uploadPath = request.getRequestURL().toString().replace(request.getServletPath(), "");
		response.getWriter().write("{\"errno\":0,\"data\":[\""+uploadPath+"/upload/"+fileName+"\"]}");
		response.getWriter().flush();
		response.getWriter().close();
	}
}
